package com.studyv3.test.controller;


import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.studyv3.common.annotation.RepeatSubmit;
import com.studyv3.common.core.controller.BaseController;
import com.studyv3.common.core.domain.AjaxResult;
import com.studyv3.common.core.domain.R;
import com.studyv3.common.core.domain.entity.SysRole;
import com.studyv3.common.core.domain.entity.SysUser;
import com.studyv3.common.core.page.PageQuery;
import com.studyv3.common.core.page.TableDataInfo;

import com.studyv3.common.core.page.TableDataInfoPlus;
import com.studyv3.common.utils.StringUtils;
import com.studyv3.common.utils.poi.ExcelUtil;
import com.studyv3.common.utils.poi.ExcelUtilPlus;
import com.studyv3.test.domain.StudyBook;
import com.studyv3.test.domain.StudyBookTypes;
import com.studyv3.test.domain.bo.StudyBookBo;
import com.studyv3.test.domain.vo.StudyBookVo;
import com.studyv3.test.service.IStudyBookService;
import com.studyv3.test.service.IStudyBookTypesService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】
 *
 * @author ruoyi
 * @date 2024-04-24
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/test/book")
public class StudyBookController extends BaseController {

    private final IStudyBookService iStudyBookService;
    private final IStudyBookTypesService iStudyBookTypesService;

    /**
     * 查询【请填写功能名称】列表
     */
    @GetMapping("/list")
    public TableDataInfoPlus<StudyBookVo> list(StudyBookBo bo, PageQuery pageQuery) {
        return iStudyBookService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PostMapping("/export")
    public void export(StudyBookBo bo, HttpServletResponse response) {
        List<StudyBookVo> list = iStudyBookService.queryList(bo);
        ExcelUtilPlus.exportExcel(list    , "书籍信息", StudyBookVo.class, response);


    }
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<StudyBook> util = new ExcelUtil<StudyBook>(StudyBook.class);
        List<StudyBook> studyBookList = util.importExcel(file.getInputStream());
        if (ObjectUtil.isEmpty(studyBookList)){
            return error("导入失败");
        }
        if (!iStudyBookService.saveOrUpdateBatch(studyBookList)){
            return error("导入失败");
        }
        return success("导入成功");
    }
//    /**
//     * 获取【请填写功能名称】详细信息
//     *
//     * @param id 主键
//     */
//    @GetMapping("/{id}")
//    public R<StudyBookVo> getInfo(@NotNull(message = "主键不能为空")
//                                     @PathVariable Long id) {
//
//        return R.ok(iStudyBookService.queryById(id));
//    }


    /**
     * 根据书籍id获取书籍信息，用于前端 add和update之前的表单数据填充
     */
    @GetMapping(value = {"/", "/{id}"})
    public AjaxResult getInfoForAddAndUpdate(@PathVariable(value = "id", required = false)
                                             @JsonSerialize(using = ToStringSerializer.class)
                                             Long bookId) {
//        iStudyBookService.checkUserDataScope(userId);
        // 1.异步请求成功
        AjaxResult ajax = AjaxResult.success();
        // 2.加载选项
        // 若数据量不是很大，可以将某些数据项在此加载返回给前端，前端来控制分页等操作
        // 若数据量很大，则需要调用controller，在点击下拉时触发分页请求。
        List<StudyBookTypes> list = iStudyBookTypesService.list();
        ajax.put("book_types", list);
        if (StringUtils.isNotNull(bookId)) {
            StudyBook studyBook = iStudyBookService.getBaseMapper().selectById(bookId);
            // 1.返回数据本身
            ajax.put(AjaxResult.DATA_TAG, studyBook);
//            ajax.put("postIds", postService.selectPostListByUserId(userId));

            // 2.返回 当前用户对应的所有角色id ，省去前端再次遍历一一对应的操作
//            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));

        }
        return ajax;
    }

    /**
     * 新增【请填写功能名称】
     */
    @RepeatSubmit()
    @PostMapping("/add")
    public AjaxResult add(@RequestBody StudyBook bo) {

        return toAjax(iStudyBookService.save(bo));
    }

    /**
     * 修改【请填写功能名称】
     */
    @RepeatSubmit()
    @PutMapping()
    public AjaxResult edit(@RequestBody StudyBookBo bo) {
        return toAjax(iStudyBookService.updateByBo(bo));
    }

    /**
     * 删除【请填写功能名称】
     *
     * @param ids 主键串
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@NotEmpty(message = "主键不能为空")
                             @PathVariable Long[] ids) {
        return toAjax(iStudyBookService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
}
